//
//  SearchViewController.m
//  ToYourHeartNews
//
//  Created by XJing on 16/1/28.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchTableViewCell.h"
#import "AfNetWorkingHandler.h"
#import "AllModel.h"
#import "AllDetailModel.h"
#import "SearchModel.h"
#import "PushWebViewVC.h"
#import "AllDetailModel.h"
#import "CellDetailTableViewCell.h"
#import <UIImageView+WebCache.h>
#import "BlackManager.h"
#import "SetBlack.h"
#import "MBProgressHUDManager.h"//小菊花
@interface SearchViewController ()<UISearchBarDelegate, UISearchResultsUpdating, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain)UISearchController *search;/**< 搜索控制视图 */
@property (nonatomic, retain)NSString *strHight;/**< 高亮用字符串 保存搜索信息 */
@property (nonatomic, retain)UIWebView *webVC;
@property (nonatomic, retain)UITableView *tableView;/**< 用来显示搜索出来的内容 */
@property (nonatomic, retain)NSMutableArray *dataArr;/**< 保存点击进入详情的数据 */
@property (nonatomic, retain)NSMutableArray *searchArr;/**< 接收搜索出来的数据 */
@property (nonatomic, retain)NSMutableArray *idArr;/**< 保存所有内容的id */
@property (nonatomic, retain)NSMutableArray *systemIdArr;/**< 存放系统中所有id */
@property (nonatomic, retain)UIImageView *backImg;
@property (nonatomic, assign)NSInteger i;//计数
@end

@implementation SearchViewController
- (void)dealloc
{
    [_dingyueArr release];
    [_search release];
    [_strHight release];
    [_webVC release];
//    [_tableView release];
    [_dataArr release];
    [_searchArr release];
    [_idArr release];
    [_systemIdArr release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //    搜索步骤:
    //    1.初始化搜索视图
    //    2.搜索视图签订协议
    //    3.设置搜索视图
    //    4.在搜索视图的协议方法中 获取输入内容 对搜索内容解析数据 刷新tableView
    //    5.在tableVIewCell方法中设置高亮 NSMutableAttributedString
    self.search = [[UISearchController alloc]initWithSearchResultsController:nil];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-newlisticon06"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)] autorelease];
    //签订协议
    _search.searchResultsUpdater = self;
    //屏幕变灰 默认是yes tableView不能拉
    _search.dimsBackgroundDuringPresentation = NO;
    //设置点击搜索框时 隐藏导航栏
    _search.hidesNavigationBarDuringPresentation = NO;
    //占位符 默认search
    _search.searchBar.placeholder = @"搜索内容";
    //搜索栏的风格
    _search.searchBar.searchBarStyle = UISearchBarStyleMinimal;
    //把搜索视图加到导航栏上
    self.navigationItem.titleView = _search.searchBar;
    //创建tableView
    self.i = 0;
    [self creatTableView];
    [_search release];
}
-(void)creatTableView
{
    self.backImg = [[UIImageView alloc]initWithFrame:self.view.frame];
    [_backImg setImage:[UIImage imageNamed:@"backImg"]];
    [self.view addSubview:_backImg];
   
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
//    _tableView.contentInset = UIEdgeInsetsMake(100, 0, 0, 0);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_tableView];
    [_tableView release];
    [_tableView registerClass:[SearchTableViewCell class] forCellReuseIdentifier:@"cellSearch"];
    //已有的cell
    [_tableView registerClass:[CellDetailTableViewCell class] forCellReuseIdentifier:@"nnCell"];
    [_tableView registerClass:[CellDetailTableViewCell class] forCellReuseIdentifier:@"mmCell"];
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, 64, 0);
    
   
    [_tableView release];
    [_backImg release];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_searchArr.count == 0) {
        [self.view.superview addSubview:_backImg];
    }else{
        [self.view bringSubviewToFront:_tableView];
    }
    return _searchArr.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.view.frame.size.height / 5;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AllDetailModel *m = _searchArr[indexPath.row];
    PushWebViewVC *detailVC = [[PushWebViewVC alloc]init];
    //    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:detailVC];
    detailVC.model = m;
    detailVC.pathstr = m.weburl;
    [self.navigationController pushViewController:detailVC animated:YES];
    [detailVC release];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //查询已有的新闻
    AllDetailModel *m = _searchArr[indexPath.row];
    if (m.media.count == 0) {
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"mmCell"];
        [SetBlack setCellColorWithCell:cell];
        [SetBlack setLableTitleColorWithArr:@[cell.textLabel]];
        cell.textLabel.text = m.title;
        cell.detailTextLabel.text = [[m.auther_name stringByAppendingString:@"  "] stringByAppendingString:m.date];
        cell.detailTextLabel.textColor = [UIColor grayColor];
//        [cell release];
        return cell;
    }else{
        CellDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"nnCell"];
        //夜间模式时
        [SetBlack setCellColorWithCell:cell];
        [SetBlack setLableTitleColorWithArr:@[cell.contentLable]];
        //cell内容赋值
        cell.writerLable.text = m.auther_name;
        cell.timeLable.text = m.date;
        NSString *img = [m.media.firstObject objectForKey:@"url"];
        [cell.picture sd_setImageWithURL:[NSURL URLWithString:img]placeholderImage:[UIImage imageNamed:@"pocket.png"]];
        //关键字高亮
        NSMutableAttributedString *light = [[NSMutableAttributedString alloc]initWithString:m.title];
        //获取标红的位置和长度
        NSRange range = [m.title rangeOfString:_strHight];
        [light setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:range];
        cell.contentLable.attributedText = light;
        return cell;
    }

}
-(void)backAction
{
    [self dismissViewControllerAnimated:YES completion:^{
        //
    }];
}
#pragma mark - 实现搜索栏协议方法
//只要搜索栏有内容 就执行下面的方法
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    
    //将搜索内容转换为字符串
    //等同于 获取搜索的信息 显示的文本
    self.strHight = [self.search.searchBar text];
    self.searchArr = [NSMutableArray array];
    if ([_strHight containsString:@" "]) {
        //判断如果有空格不执行
        //没有执行以下程序
        //不写这个判断 打空格就会崩溃
    }else{
       
       
        NSString *str = @"http://iphone.myzaker.com/zaker/daily_hot.php?app_id_4=310000";
        [AfNetWorkingHandler GetWithStr:str complection:^(id result) {
            //
            [MBProgressHUDManager showHUDtoView:self.view string:@"努力加载中"];
            NSArray *arr = result[@"data"][@"articles"];
            NSArray *modelArr = [AllDetailModel modelHanderWithArray:arr];
            for (AllDetailModel *model in modelArr) {
                NSString *title = model.title;
                if ([title containsString:_strHight]) {
                    [self.searchArr addObject:model];
                    if (_searchArr.count != 0) {
                        [_backImg removeFromSuperview];
                    }
                }
                
        
            }
            //判断没有搜索到内容是显示
            if (![_search.searchBar.text isEqualToString:@""] && _searchArr.count == 0) {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"没有您要搜索的内容" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alert show];
                [alert release];
            }

            [_tableView reloadData];
            [MBProgressHUDManager removeHUD];
        }];
    }
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
